class InvitationsController < ApplicationController
  
  before_filter :login_required, :except => 'show'
  before_filter :identify_group, :except => 'show'
  
  # GET /invitations
  # GET /invitations.xml
  def index
    @invitations = @group.invitations

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @invitations }
    end
  end

  # GET /invitations/1
  # GET /invitations/1.xml
  def show
    @invitation = Invitation.find_by_key(params[:id])
    session[:key] = @invitation.key
    redirect_to(new_group_membership_path(@invitation.group))
  end

  # GET /invitations/new
  # GET /invitations/new.xml
  def new
    @invitation = Invitation.new
    @invitation.group = @group
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @invitation }
    end
  end

  # GET /invitations/1/edit
  def edit
    @invitation = Invitation.find(params[:id])
  end

  # POST /invitations
  # POST /invitations.xml
  def create

    @invitation = Invitation.new(params[:invitation])
    @invitation.group = @group
    @invitation.creator = current_user
    
    respond_to do |format|
      if @invitation.save()
        UserMailer.deliver_group_invitation(@invitation) 
        flash[:notice] = 'Invitation was successfully created.'
        format.html { redirect_to(@group) }
        format.xml  { render :xml => @invitation, :status => :created, :location => @group }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @invitation.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /invitations/1
  # PUT /invitations/1.xml
  def update
    @invitation = Invitation.find(params[:id])

    respond_to do |format|
      if @invitation.update_attributes(params[:invitation])
        flash[:notice] = 'Invitation was successfully updated.'
        format.html { redirect_to(@group) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @invitation.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /invitations/1
  # DELETE /invitations/1.xml
  def destroy
    @invitation = Invitation.find(params[:id])
    @invitation.destroy

    respond_to do |format|
      format.html { redirect_to(@group) }
      format.xml  { head :ok }
    end
  end
  
  private
  
  def identify_group
    @group = Group.find(params[:group_id])
  end
    
end
